package com.wdzl;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class QQFriendsInterfacet extends JFrame {
    private static final int WIDTH = 320;
    private static final int HEIGHT = 600;

    // 界面组件
    private JTextField searchField;
    private JList<String> friendsList;
    private DefaultListModel<String> listModel;
    private DefaultListModel<String> originalListModel; // 存储原始数据
    private Map<String, List<String>> friendGroups;
    private Map<String, Boolean> groupExpanded;
    private String searchKeyword = ""; // 搜索关键词
    private boolean isSearchMode = false; // 是否处于搜索模式

    public QQFriendsInterfacet() {

        new MainFrame("我").setVisible( true);
        // 初始化数据
        initData();

        // 设置窗口
        setTitle("QQ好友界面");
        setSize(WIDTH, HEIGHT);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setResizable(false);

        // 设置界面
        initUI();

        // 添加事件处理
        addEventHandlers();

        setVisible(true);
    }

    private void initData() {
        friendGroups = new HashMap<>();
        groupExpanded = new HashMap<>();

        // 添加好友分组数据
        List<String> group1 = new ArrayList<>();
        group1.add("张三");
        group1.add("李四");
        group1.add("王五");

        List<String> group2 = new ArrayList<>();
        group2.add("同事A");
        group2.add("同事B");

        List<String> group3 = new ArrayList<>();
        group3.add("同学甲");
        group3.add("同学乙");
        group3.add("同学丙");
        group3.add("同学丁");

        friendGroups.put("我的好友", group1);
        friendGroups.put("同事", group2);
        friendGroups.put("同学", group3);

        // 默认所有分组展开
        for (String group : friendGroups.keySet()) {
            groupExpanded.put(group, true);
        }
    }

    private void initUI() {
        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        // 顶部搜索面板
        mainPanel.add(createTopPanel(), BorderLayout.NORTH);

        // 中部好友列表
        mainPanel.add(createFriendsListPanel(), BorderLayout.CENTER);

        // 底部功能按钮
        mainPanel.add(createBottomPanel(), BorderLayout.SOUTH);

        setContentPane(mainPanel);
    }

    private JPanel createTopPanel() {
        JPanel panel = new JPanel(new BorderLayout(5, 5));
        panel.setBackground(new Color(45, 183, 245));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 搜索框
        searchField = new JTextField("搜索联系人、群聊、公众号");
        searchField.setForeground(Color.GRAY);
        searchField.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        searchField.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));

        // 清除搜索按钮
        JButton clearButton = new JButton("×");
        clearButton.setForeground(Color.WHITE);
        clearButton.setFont(new Font("微软雅黑", Font.BOLD, 12));
        clearButton.setContentAreaFilled(false);
        clearButton.setBorderPainted(false);
        clearButton.setVisible(false); // 初始隐藏
        clearButton.setActionCommand("clear");

        // 设置按钮
        JButton settingsButton = new JButton("设置");
        settingsButton.setForeground(Color.WHITE);
        settingsButton.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        settingsButton.setContentAreaFilled(false);
        settingsButton.setBorderPainted(false);

        // 将清除按钮和设置按钮放入一个面板，便于布局
        JPanel rightPanel = new JPanel(new BorderLayout(5, 0));
        rightPanel.add(clearButton, BorderLayout.WEST);
        rightPanel.add(settingsButton, BorderLayout.EAST);
        panel.add(searchField, BorderLayout.CENTER);
        panel.add(rightPanel, BorderLayout.EAST);

        return panel;
    }

    private JPanel createFriendsListPanel() {
        JPanel panel = new JPanel(new BorderLayout());

        // 初始化原始列表模型
        originalListModel = new DefaultListModel<>();
        updateOriginalListModel();

        // 初始化显示列表模型
        listModel = new DefaultListModel<>();
        updateListModel();

        // 创建好友列表
        friendsList = new JList<>(listModel);
        friendsList.setCellRenderer(new FriendsListRenderer());
        friendsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        // 添加滚动条
        JScrollPane scrollPane = new JScrollPane(friendsList);
        scrollPane.setBorder(BorderFactory.createEmptyBorder());

        panel.add(scrollPane, BorderLayout.CENTER);
        return panel;
    }

    private void updateOriginalListModel() {
        originalListModel.clear();
        for (String group : friendGroups.keySet()) {
            boolean expanded = groupExpanded.get(group);
            String groupLabel = expanded ? "▼ " + group : "▶ " + group;
            originalListModel.addElement(groupLabel);

            if (expanded) {
                for (String friend : friendGroups.get(group)) {
                    originalListModel.addElement("  " + friend);
                }
            }
        }
    }

    private void updateListModel() {
        listModel.clear();

        if (isSearchMode && !searchKeyword.isEmpty()) {
            // 搜索模式：显示匹配的好友
            boolean hasResults = false;

            // 先添加分组标题（仅显示有匹配好友的分组）
            for (String group : friendGroups.keySet()) {
                boolean expanded = groupExpanded.get(group);
                String groupLabel = expanded ? "▼ " + group : "▶ " + group;

                List<String> friends = friendGroups.get(group);
                List<String> matchedFriends = new ArrayList<>();

                // 查找匹配的好友
                for (String friend : friends) {
                    if (friend.contains(searchKeyword)) {
                        matchedFriends.add(friend);
                    }
                }

                if (!matchedFriends.isEmpty()) {
                    listModel.addElement(groupLabel);
                    hasResults = true;

                    if (expanded) {
                        for (String friend : matchedFriends) {
                            listModel.addElement("  " + friend);
                        }
                    }
                }
            }

            // 如果没有找到匹配的好友，显示提示信息
            if (!hasResults) {
                listModel.addElement("没有找到匹配的联系人");
            }
        } else {
            // 正常模式：显示所有好友
            for (int i = 0; i < originalListModel.size(); i++) {
                listModel.addElement(originalListModel.getElementAt(i));
            }
        }
    }

    private JPanel createBottomPanel() {
        JPanel panel = new JPanel(new GridLayout(1, 4, 5, 5));
        panel.setBackground(new Color(245, 245, 245));
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        // 底部功能按钮
        String[] buttonTexts = {"消息", "联系人", "发现", "我"};
        for (String text : buttonTexts) {
            JButton button = new JButton(text);
            button.setFont(new Font("微软雅黑", Font.PLAIN, 12));
            button.setForeground(new Color(100, 100, 100));
            button.setContentAreaFilled(false);
            button.setBorderPainted(false);
            panel.add(button);
        }

        return panel;
    }

    private void addEventHandlers() {
        // 搜索框事件
        searchField.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                if (searchField.getText().equals("搜索联系人、群聊、公众号"))
                {
                    searchField.setText("");
                    searchField.setForeground(Color.BLACK);

                    // 显示清除按钮
                    JPanel rightPanel = (JPanel) searchField.getParent().getComponent(1);
                    JButton clearButton = (JButton) rightPanel.getComponent(0);
                    clearButton.setVisible(true);
                }
            }

            @Override
            public void focusLost(FocusEvent e) {
                if (searchField.getText().isEmpty()) {
                    searchField.setText("搜索联系人、群聊、公众号");
                    searchField.setForeground(Color.GRAY);

                    // 隐藏清除按钮
                    JPanel rightPanel = (JPanel) searchField.getParent().getComponent(1);
                    JButton clearButton = (JButton) rightPanel.getComponent(0);
                    clearButton.setVisible(false);
                }
            }
        });

        // 搜索框文本变化事件
        searchField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                String text = searchField.getText().trim();

                if (text.isEmpty()) {
                    // 清空搜索框，退出搜索模式
                    searchKeyword = "";
                    isSearchMode = false;

                    // 隐藏清除按钮
                    JPanel rightPanel = (JPanel) searchField.getParent().getComponent(1);
                    JButton clearButton = (JButton) rightPanel.getComponent(0);
                    clearButton.setVisible(false);
                } else {
                    // 设置搜索关键词
                    searchKeyword = text;
                    isSearchMode = true;
                }

                // 更新列表
                updateListModel();
            }
        });

        // 清除按钮事件
        JPanel topPanel = (JPanel) searchField.getParent();
        JPanel rightPanel = (JPanel) topPanel.getComponent(1);
        JButton clearButton = (JButton) rightPanel.getComponent(0);
        clearButton.addActionListener(e -> {

            searchField.setText("");
            searchField.setForeground(Color.GRAY);
            searchKeyword = "";
            isSearchMode = false;
            updateListModel();
            clearButton.setVisible(false);

        });

        // 好友列表点击事件
        friendsList.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int index = friendsList.locationToIndex(e.getPoint());
                if (index >= 0) {
                    String selectedItem = listModel.getElementAt(index);

                    // 检查是否是分组或提示信息
                    if (selectedItem.startsWith("▼ ") || selectedItem.startsWith("▶ ") ||
                            selectedItem.equals("没有找到匹配的联系人")) {
                        return; // 不处理分组和提示信息的点击
                    }

                    // 显示确认对话框
                    int option = JOptionPane.showOptionDialog(
                            QQFriendsInterfacet.this,
                            "您点击了好友: " + selectedItem.trim(),
                            "好友点击",
                            JOptionPane.YES_NO_OPTION,
                            JOptionPane.QUESTION_MESSAGE,
                            null,
                            new Object[]{"确定", "取消"},
                            "确定"
                    );

                    // 如果用户点击“确定”，则创建并显示新的 MainFrame 窗口
                    if (option == JOptionPane.YES_OPTION) {
                        new MainFrame(selectedItem.trim()).setVisible( true); // 假设 MainFrame 是一个已经定义好的 JFrame 子类
                    }
                }
            }
        });

    }

    // 自定义列表渲染器，支持搜索关键词高亮
    private class FriendsListRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index,
                                                      boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

            String text = (String) value;

            if (text.startsWith("▼ ") || text.startsWith("▶ ")) {
                // 分组项
                setFont(new Font("微软雅黑", Font.BOLD, 14));
                setForeground(new Color(100, 100, 100));
                setBackground(new Color(240, 240, 240));
                setIcon(null);
            } else if (text.equals("没有找到匹配的联系人")) {
                // 搜索无结果提示
                setFont(new Font("微软雅黑", Font.ITALIC, 12));
                setForeground(new Color(150, 150, 150));
                setIcon(null);
            } else {
                // 好友项，使用系统默认的用户图标
                setFont(new Font("微软雅黑", Font.PLAIN, 14));
                setForeground(Color.BLACK);
                setIcon(UIManager.getIcon("Tree.leafIcon"));

                // 搜索关键词高亮
                if (isSearchMode && !searchKeyword.isEmpty() && text.contains(searchKeyword)) {

                    // 分割文本为三部分：关键词前、关键词、关键词后
                    int startIndex = text.indexOf(searchKeyword);
                    int endIndex = startIndex + searchKeyword.length();
                    String part1 = text.substring(0, startIndex);
                    String part2 = text.substring(startIndex, endIndex);
                    String part3 = text.substring(endIndex);

                    // 拼接为 HTML 文本，仅高亮关键词
                    String highlightedText = String.format(
                            "<html>%s<span style='color:red; font-weight:bold;'>%s</span>%s</html>",
                            part1, part2, part3
                    );
                    setText(highlightedText);
                    setIconTextGap(5);
                } else {
                    // 正常显示文本
                    setText(text);
                }
            }

            // 选中状态
            if (isSelected) {
                setBackground(new Color(220, 240, 255));
            }

            return this;
        }
    }

}
